<template>
  <div class="flex flex-wrap">
    <!-- 先预览，然后再自定义上传base64图片 -->
    <div
      class="w-[104px] h-[104px] p-[8px] mr-[8px] mb-[8px] relative learn-top-sub"
      style="border: 1px solid #d9d9d9"
      v-if="previewList.length > 0"
      v-for="(item, index) in previewList"
      :key="item.uid"
    >
      <img alt="example" class="w-[86px] h-[86px] object-contain" :src="item.url" />
      <div class="mask-img z-100 px-[15px]">
        <zoom-in-outlined class="text-[17px] cursor-pointer" @click.stop="handleNormalPreview(item.url)" />
        <delete-outlined class="text-[17px] cursor-pointer" @click.stop="handleDel(index)" />
      </div>
    </div>
    <div class="clearfix">
      <a-upload
        listType="picture-card"
        :fileList="fileList"
        :beforeUpload="beforeUpload"
        :max-count="maxCount"
        :multiple="true"
        @change="handleChange"
        @preview="handlePreview"
        @remove="handleRemove"
      >
        <div v-if="previewList.length + fileList.length < maxCount">
          <plus-outlined />
          <div style="margin-top: 8px">点击上传</div>
        </div>
      </a-upload>
      <!-- 放大预览窗口 -->
      <a-modal
        v-model:visible="normalPreviewVisible"
        :maskClosable="false"
        :footer="null"
        :afterClose="handleAfterClose"
        @cancel="normalHandleCancel"
      >
        <img alt="example" style="width: 100%" :src="normalPreviewImage" />
      </a-modal>
      <!-- 放大预览窗口 -->
      <a-modal v-model:visible="previewVisible" :maskClosable="false" :footer="null" @cancel="handleCancel">
        <img alt="example" style="width: 100%" :src="previewImage" />
      </a-modal>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { message } from 'ant-design-vue'
import { ref, watch, inject, computed } from 'vue'
import apis from '@/apis'
import type { UploadChangeParam } from 'ant-design-vue'
const emit = defineEmits(['getImageInfo'])
const {
  permission: { multiple_upload }
} = apis
const imageDomain = inject('imageDomain') as any
const baseUrl = computed(() => imageDomain?.atlas_content_cover || window.location.origin + '/')
const props = withDefaults(defineProps<{ maxCount: number; fileLists: any; index: number }>(), {
  maxCount: 100,
  fileLists: undefined,
  index: 0
})
const isUpload = ref(false)
const fileList: any = ref([])
const previewList: any = ref([])
const previewVisible = ref(false)
const normalPreviewVisible = ref(false)
const previewImage = ref('')
const normalPreviewImage = ref('')
const uploading = ref(false)

//上传前
const beforeUpload = (file: any) => {
  // console.log('file: ', file)
  // //图片格式限制为 jpeg、png
  // const imageType = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp']
  // const isJpgOrPng = imageType.includes(file.type)
  // if (!isJpgOrPng) {
  //   message.error('只支持后缀为 .jpg .jpeg .png .bmp .gif 的图片')
  //   return false
  // }
  // //图片大小限制为 2M以内
  // const isLt10M = file.size / 1024 / 1024 <= 10
  // if (!isLt10M) {
  //   message.error('图片大小不能超过10MB，请重新上传')
  //   return false
  // }
  // if (fileList.value.length > props.maxCount) {
  //   //判断上传的图片数量
  //   return false
  // }
  exeBase(file)
  return false
}
const handleNormalPreview = (url: string) => {
  console.log('url: ', url)
  normalPreviewVisible.value = true
  normalPreviewImage.value = url
}
const handleDel = (index: number) => {
  previewList.value.splice(index, 1)
  let newFile = previewList.value
    .filter((item: any) => item.status && item.status === 'done')
    .map((item: any) => item.url.replace(baseUrl.value, ''))
  emit('getImageInfo', newFile, props.index)
}
//去重
const exeBase = async (file: any) => {
  console.log('file: ', file)
  await getBase64(file, (imageUrl: string) => {
    // if (fileList.value.length < props.maxCount && preventRepeat(imageUrl)) {
    if (fileList.value.length < props.maxCount) {
      console.log('fileList.value123123: ', fileList.value)
      //判断图片数量及去重
      const file2 = file
      file2.url = imageUrl
      fileList.value = [...fileList.value, file] as any
      isUpload.value = true
      uploading.value = false
    }
  }).then((result: any) => {
    console.log(result)
  })
}
const handleChange = (info: UploadChangeParam) => {
  // console.log('file,fileList: ', info.file, info.fileList)
  // console.log('fileList.value: ', fileList.value)
  // fileList.value = info.fileList
  // fileList.value = info.fileList
}
const handleRemove = (file: any) => {
  //删除图片
  const index = fileList.value.indexOf(file)
  const newFileList = fileList.value.slice()
  newFileList.splice(index, 1)
  fileList.value = newFileList
  isUpload.value = true
}
const getBase64 = (file: any, callback: any) => {
  return new Promise((resolve) => {
    let reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => {
      callback(reader.result)
      resolve('成功')
    }
  })
}
const preventRepeat = (url: string) => {
  // 排除相同图片
  for (let i = 0, len = fileList.value.length; i < len; i++) {
    if (fileList.value[i].url === url) {
      return false
    }
  }
  return true
}
const handleAfterClose = () => {
  normalPreviewImage.value = ''
}
const normalHandleCancel = () => {
  normalPreviewVisible.value = false
}
const handleCancel = () => {
  //点击关闭图片预览
  previewVisible.value = false
}
const handlePreview = async (file: any) => {
  console.log('file: ', file.originFileObj)
  //点击查看大图
  if (!file.url && !file.preview) {
    file.preview = await getBase64(file.originFileObj, null)
  }
  previewImage.value = file.url || file.preview
  previewVisible.value = true
}
const getFileList = (val: any) => {
  const list = val
  if (!list.picture_url) return []
  const lists = list.picture_url.indexOf('\n') === -1 ? [list.picture_url] : list.picture_url.split('\n')
  const photo = lists.map((item: any, index: number) => {
    return {
      uid: list.chapter_no + index,
      status: 'done',
      url: baseUrl.value + item
    }
  })
  previewList.value = [...photo]
  console.log('photo: ', photo)
  console.log('previewList.value: ', previewList.value)
}
watch(
  () => props.fileLists,
  (val) => {
    console.log('props============================list: ', val)
    if (!val.picture_url) return (previewList.value.length = [])
    getFileList(val)
  },
  {
    immediate: true,
    deep: true
  }
)
watch(
  () => fileList.value,
  (val: any) => {
    console.log('file文件========================: ', val)
  },
  {
    deep: true
  }
)
//开始上传
const handleUpload = () => {
  console.log('fileList.value: ', fileList.value)
  if (fileList.value.length === 0) return message.warning('您还没有上传新的图片')
  if (!isUpload.value) return message.warning('图片未更改，无需保存')
  console.log('fileList111111111111111: ', fileList.value)
  let newFile = previewList.value
    .filter((item: any) => item.status && item.status === 'done')
    .map((item: any) => item.url.replace(baseUrl.value, ''))

  console.log('newFile: ', newFile)
  const formData = new FormData()
  fileList.value.forEach((file: any) => {
    formData.append('files', file) //后面再加上token
  })

  console.log('fileList222222222222222: ', fileList.value)
  formData.append('img_type', '2')
  uploading.value = true
  multiple_upload(formData)
    .then((res: any) => {
      console.log('res: ', res)
      if (res.data.fail_files && res.data.fail_files.length > 0) {
        message.warning(res.data.msg)
        fileList.value = []
      } else {
        message.success(res.data.msg)
      }
      isUpload.value = false
      // const url = newFile + '\\n/' + res.data.urls.join('\\n/')
      // console.log('newFile + res.data.urls: ', url)
      const urlList = newFile.length > 0 ? [...res.data.urls, ...newFile] : res.data.urls
      console.log('urlList: ', urlList)
      emit('getImageInfo', urlList, props.index)
      fileList.value = []
    })
    .catch(() => {
      isUpload.value = false
    })
}
defineExpose({
  handleUpload,
  fileList
})
</script>

<style lang="less" scoped>
.learn-top-sub:hover .mask-img {
  opacity: 1;
  cursor: default;
}
.mask-img {
  position: absolute;
  width: 100%;
  height: 100%;
  bottom: 0;
  left: 0;
  background: rgba(101, 101, 101, 0.6);
  color: #ffffff;
  opacity: 0;
  display: flex;
  align-items: center;
  justify-content: space-around;
}
:deep(.ant-upload-list-picture-card-container) {
  // display: none;
}

.ant-upload-text {
  font-size: 12px;
  color: #8e8e8e;
}

// .choose-button {
//   font-size: 12px;
//   color: #262626;
// }
</style>
